const autoFile = require("../service/autoFile");
const { sys_form, op } = require("../../middleware/baseModel");

module.exports = {
  "GET /sys_form/all": async (ctx, next) => {
    const res = await sys_form.findAll();
    return ctx.success(res);
  },

  "GET /sys_form/detail": async (ctx, next) => {
    let id = ctx.get("id");
    const res = await sys_form.findOne({
      where: { id: id },
      include: [
        { association: sys_form.associations.menu, attributes: ["id", "name"] },
        { association: sys_form.associations.model, attributes: ["key", "name"] },
      ],
    });
    return ctx.success(res);
  },

  "POST /sys_form/generate": async (ctx, next) => {
    let form_id = ctx.get("id");
    if (form_id) {
      const sysFormRow = await sys_form.findOne({ where: { id: form_id } });
      if (sysFormRow) {
        let { menu_id, model_id } = sysFormRow;
        await autoFile.createForm(menu_id, model_id);
        await autoFile.autoFrontEndApi(menu_id);
        await autoFile.autoFrontEndVue(menu_id);
        return ctx.success("生成成功");
      }
    }
    return ctx.fail("生成失败");
  },

  "POST /sys_form/page": async (ctx, next) => {
    let param = ctx.getPageSize();
    let row = ctx.getBody();
    let { key, value } = row.seachOption;
    let where = {};
    if (key && value) {
      where[key] = { [op.like]: "%" + value + "%" };
    }

    const res = await sys_form.findAndCountAll({
      where,
      include: [
        { association: sys_form.associations.menu, attributes: ["id", "name"] },
        { association: sys_form.associations.model, attributes: ["key", "name"] },
      ],
      order: [["id", "DESC"]],
      ...param,
    });
    return ctx.success(res);
  },

  "POST /sys_form/add": async (ctx, next) => {
    let row = ctx.getBody();
    const res = await sys_form.create(row);
    return ctx.success(res);
  },
  "POST /sys_form/edit": async (ctx, next) => {
    let row = ctx.getBody();
    let id = ctx.get("id");
    const res = await sys_form.update(row, { where: { id: id } });
    return ctx.success(res);
  },

  "POST /sys_form/del": async (ctx, next) => {
    let id = ctx.get("id");
    const res = await sys_form.destroy({ where: { id: id } });
    return ctx.success(res);
  },
};
